import { Injectable, Logger } from "@nestjs/common";
import OSS from 'ali-oss';

@Injectable()
export class AliyunOssService {
	private readonly logger = new Logger(AliyunOssService.name)
	private client: any;

	constructor() {
		this.client = new OSS({
			// 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
			accessKeyId: "LTAI5tP1e7gWU3SFXYKTS88H",
			accessKeySecret: "nPOVZx7LQd7OVo0idcYuSHIQZo9Jpl",
			// yourregion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
			// region: ossConfig.region,
      bucket: "deyiluopan",
			endpoint: "oss-cn-beijing.aliyuncs.com",
		});
	}

	// 上传文件到oss 并返回  图片oss 地址
  public async putOssFile(ossPath: string, localPath: string): Promise<string> {
    let res: any;

    try {
      res = await this.client.put(ossPath, localPath)
      // 将文件设置为公共可读
      await this.client.putACL(ossPath, "public-read")
    } catch (error) {
      console.log(error)
    }

    return res.url
  }

	/**
   * 上传文件大小校验
   * @param localPath
   * @param ossPath
   * @param size
   */
  public async validateFile(ossPath: string, localPath: string, size: number): Promise<string> {
    if (size > 5 * 1024 * 1024) {
      return
    } else {
      return await this.putOssFile(ossPath, localPath)
    }
  }

}